﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using System.Diagnostics;

namespace CMSLauncher
{
    public partial class LauncherForm : Form
    {
        private string VersionPath = "/files/";
        private string VersionIni = "version.ini";
        private string StartPath = Application.StartupPath + "\\";
        private string StatusText = "";
        private const int THREAD_WAIT = 100;
        private int LaunchStatus = 0;
        private int MaxProgress = 10;

        public LauncherForm()
        {
            InitializeComponent();
        }

        private void LauncherForm_Load(object sender, EventArgs e)
        {
            timerRefresh.Start();

            Thread initThread = new Thread(new ThreadStart(InitCMS));
            initThread.Start();
        }

        private void InitCMS()
        {
            string VersionIniFile = StartPath + VersionIni;

            StatusText = "读取本地信息...";
            Thread.Sleep(THREAD_WAIT);

            int curBuildVersion = PubClass.ConvertToInt32(ConfigFile.ReadValue("Client", "BuildVersion"), -1);
            string serverIP = ConfigFile.ReadValue("ServerIP");
            string[] webPorts = { ":8080", ":80"};
            foreach (string port in webPorts)
            {
                MaxProgress += progressBarStatus.Maximum / 4 / webPorts.Length;
                try
                {
                    string urlPath = "http://" + serverIP + port + VersionPath;
                    string urlVersion = urlPath + VersionIni;
                    StatusText = "访问资源服务器 " + serverIP + port;
                    Thread.Sleep(THREAD_WAIT);

                    WebClient wc = new WebClient();
                    wc.DownloadFile(urlVersion, VersionIniFile);

                    int latestBuildVersion = PubClass.ConvertToInt32(ConfigFile.ReadValue("Client", "BuildVersion", VersionIniFile), 0);
                    string[] files = ConfigFile.ReadValue("Client", "Files", VersionIniFile).Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    if (latestBuildVersion == 0)
                    {
                        StatusText = "无法获取资源 " + urlVersion;
                        Thread.Sleep(THREAD_WAIT * 10);
                        continue;
                    }

                    foreach (string file in files)
                    {
                        MaxProgress += progressBarStatus.Maximum / 4 / files.Length;

                        try
                        {
                            if (curBuildVersion != latestBuildVersion || !File.Exists(StartPath + file))
                            {
                                StatusText = "正在下载文件 " + file;
                                Thread.Sleep(THREAD_WAIT);

                                if (!Directory.Exists(Path.GetDirectoryName(StartPath + file)))
                                    Directory.CreateDirectory(Path.GetDirectoryName(StartPath + file));
                                wc.DownloadFile(urlPath + file, StartPath + file);
                            }
                        }
                        catch
                        {
                            // 通常是下载文件失败
                        }
                    }

                    ConfigFile.WriteValue("Client", "BuildVersion", latestBuildVersion.ToString());
                    StatusText = "已更新至最新版";
                    Thread.Sleep(THREAD_WAIT);
                    break;
                }
                catch
                {
                    // 通常是无法访问到服务器
                }
            }

            string[] checkFiles = ConfigFile.ReadValue("Client", "Files", VersionIniFile).Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string file in checkFiles)
            {
                MaxProgress += progressBarStatus.Maximum / 4 / checkFiles.Length;
                StatusText = "正在加载 " + file;
                Thread.Sleep(THREAD_WAIT);
                if (!File.Exists(StartPath + file))
                {
                    StatusText = "无法启动CMS，找不到文件 " + file;
                    LaunchStatus = -1;
                    return;
                }
            }

            MaxProgress = progressBarStatus.Maximum;
            StatusText = "正在启动CMS...";
            LaunchStatus = 1;
            Thread.Sleep(THREAD_WAIT * 20);
            LaunchStatus = 10;
        }

        private void timerRefresh_Tick(object sender, EventArgs e)
        {
            timerRefresh.Stop();

            labelStatus.Text = StatusText;
            if (progressBarStatus.Value + 2 <= MaxProgress)
            {
                progressBarStatus.Value += 2;
            }

            if (LaunchStatus == 1)
            {
                //调用本体程序
                Process p = new Process();
                p.StartInfo.FileName = Application.StartupPath + "\\cms.exe";
                p.Start();
                p.Close();
                LaunchStatus = 2;
            }

            if (LaunchStatus == 10)
            {
                if (Opacity > 0)
                {
                    Opacity -= 0.1;
                }
                else
                {
                    Close();
                }
            }

            timerRefresh.Start();
        }

        private void LauncherForm_Click(object sender, EventArgs e)
        {
            if (LaunchStatus != 0)
            {
                LaunchStatus = 10;
            }
        }

        #region 其他
        private string GetUrlPath(string url)
        {
            string result = "";
            try
            {
                result = url.Substring(0, url.LastIndexOf("/") + 1);
            }
            catch { }
            return result;
        }

        private string GetHostnameByUrl(string url)
        {
            string result = "";
            try
            {
                url = url.Replace("http://", "");
                string[] temp = url.Split(new string[] { ":", "/" }, StringSplitOptions.RemoveEmptyEntries);
                result = temp[0];
            }
            catch { }
            return result;
        }
        #endregion
    }
}
